package com.vlyman.sysbase.controller;

import com.vlyman.builder.QueryWrapperBuilder;
import com.vlyman.consts.KeyConsts;
import com.vlyman.consts.UriConsts;
import com.vlyman.redis.utils.JedisUtil;
import com.vlyman.rsa.RsaUtilForJs;
import com.vlyman.rtn.RtnResult;
import com.vlyman.rtn.SystemRtn;
import com.vlyman.shiro.entity.SysUser;
import com.vlyman.shiro.jwt.JwtUtil;
import com.vlyman.shiro.service.ShiroService;
import com.vlyman.shiro.service.SysUserService;
import com.vlyman.sysbase.model.request.LoginReqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 类描述：
 *  用户登录控制器
 * @author chenjs
 * @date 2018/12/21 11:15
 **/
@Slf4j
@RestController
@RequestMapping(UriConsts.SYSBASE_USER_PREFIX)
public class UserController {

    @Autowired
    private ShiroService shiroServiceImpl;
    @Autowired
    private SysUserService sysUserServiceImpl;

    /**
     * 方法描述：
     *   用户登录
     *  @author chenjs
     *  @param params
     *  @return RtnResult
     *  @date 2018/12/22 11:52
     */
    @PostMapping("/login")
    public RtnResult login(LoginReqVo params) throws Exception {
        boolean isCodeValid = verifyCaptcha(params.getCodeId(), params.getCode());
        if (!isCodeValid) {
            throw new Exception(SystemRtn.CAPTCHA_INVALID.getCodeStr());
        }
        String login = params.getUserName();
        //从数据库获取对应用户名的用户
        SysUser user = sysUserServiceImpl.getOne(
                QueryWrapperBuilder.init(SysUser.class)
                        .eq(SysUser.LOGIN, login)
        );
        if (user == null) {
            throw new Exception(SystemRtn.NAME_INVALID.getCodeStr());
        }

        String pwd = RsaUtilForJs.decyrpt(params.getPassword());
        if (DigestUtils.sha256Hex(pwd).equals(user.getPassword())) {
            // 清除旧有用户权限
            if (JedisUtil.exist(KeyConsts.REDIS_SHIRO_CACHE_PREFIX+user.getId())) {
                JedisUtil.delKey(KeyConsts.REDIS_SHIRO_CACHE_PREFIX+user.getId());
            }
            // 返回AccessToken
            String token = JwtUtil.sign(user.getId());
            return RtnResult.success().setData(token);
        }
        throw new Exception(SystemRtn.PWD_INVALID.getCodeStr());
    }

    /**
     * 方法描述：
     *   校验验证码是否输入正确
     *  @author chenjs
     *  @param codeId 保存在redis中的验证码key
     *  @param code 前端输入的验证码
     *  @return boolean
     *  @date 2019/1/13 11:23
     */
    private boolean verifyCaptcha(Integer codeId, String code) throws Exception{
        String captcha = JedisUtil.getObjectString(KeyConsts.REDIS_CAPTCHA_PREFIX + codeId);
        if (!StringUtils.hasText(captcha)) {
            throw new Exception(SystemRtn.CAPTCHA_EXPIRED.getCodeStr());
        }
        if (captcha.equals(code)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 方法描述：
     *   重新加载shiro权限
     *  @author chenjs
     *  @return RtnResult
     *  @date 2019/1/15 10:04
     */
    @GetMapping("/reload/permision")
    public RtnResult reloadPermission() {
        shiroServiceImpl.reloadPermisson();
        return RtnResult.success();
    }

    @GetMapping("/staff/view")
    public RtnResult staffView() {
        return RtnResult.success().setRtnMsg("拥有访问staff权限");
    }

    @GetMapping("/staff/add")
    public RtnResult staffAdd() {
        return RtnResult.success().setRtnMsg("拥有添加staff权限");
    }

    @GetMapping("/area/view")
    public RtnResult areaView() {
        return RtnResult.success().setRtnMsg("拥有访问area权限");
    }
}
